var wa2_history = new Array()
var wa2_future = new Array()

function initCol(){
    var req = new XMLHttpRequest()
    req.open("GET", base+"/dbversion", true)
    req.onreadystatechange = function () {
        if (req.readyState == 4) {
          if (req.status == 200) {
              if (req.responseText) {
              setColDB(req.responseText)
              }
              }
          }
        }
    req.send("")
}
function setColDB(db) {
    dbVersion = db
    var f = $('files')
    var n = $('navtree')
    if (files_ds) {
        f.database.RemoveDataSource(files_ds)
    }
    if (dirs_ds) {
        f.database.RemoveDataSource(dirs_ds)
        n.database.RemoveDataSource(dirs_ds)
    }
    if (artists_ds) {
        f.database.RemoveDataSource(artists_ds)
        n.database.RemoveDataSource(artists_ds)
    }
    if (albums_ds) {
        f.database.RemoveDataSource(albums_ds)
        n.database.RemoveDataSource(albums_ds)
    }
    dirs_ds = rdfService.GetDataSource(base+"/static/rdf/dirs-"+db+".xml")
    artists_ds = rdfService.GetDataSource(base+"/static/rdf/artists-"+db+".xml")
    albums_ds = rdfService.GetDataSource(base+"/static/rdf/albums-"+db+".xml")
    files_ds = rdfService.GetDataSource(base+"/static/rdf/songs-"+db+".xml")
    n.database.AddDataSource(dirs_ds)
    n.database.AddDataSource(artists_ds)
    n.database.AddDataSource(albums_ds)
    f.database.AddDataSource(files_ds)
    f.database.AddDataSource(dirs_ds)
    f.database.AddDataSource(artists_ds)
    f.database.AddDataSource(albums_ds)
    if (playlists_ds) {
        playlists_ds.Refresh(true)
    }
    else {
        playlists_ds = rdfService.GetDataSource(base + "/static/rdf/playlists.xml")
        playlists_ds.QueryInterface(Components.interfaces.nsIRDFRemoteDataSource)
        n.database.AddDataSource(playlists_ds)
        f.database.AddDataSource(playlists_ds)
    }
    n.ref="nav_root"
    f.ref=""
    $('files').disabled = false
    $('navtree').disabled = false
}


function showDir(e) {
  var tree = $('navtree')
  var id = tree.view.getCellValue(tree.currentIndex,tree.columns.getNamedColumn('navname'))
  var mytype = tree.view.getCellValue(tree.currentIndex,tree.columns.getNamedColumn('navtype'))
  if (mytype == "playlist" && id == '0') {
      playlists_ds.refresh()
    }
  getDir(mytype, id)
}
function getDir(mytype, id) {
    $('wa2_search').value='';
    $('search_deck').selectedIndex=0
    //Add to history only if it is a new location.
    if (wa2_history.length > 0) {
        //comparing array to array doesn't work in javascript...
        if (wa2_history[0][0] != mytype || wa2_history[0][1] != id) {
            wa2_history.unshift([mytype, id])
        }
    }
    else {wa2_history.unshift([mytype, id])}
    $('files_back').disabled=false
    if (wa2_history.length > 9) {wa2_history.length = 10}
    var f = $('files')
    if (content_ds) {
        f.database.RemoveDataSource(content_ds)
        }
    if (id != '0' && id != 'top'){
        var content_ds = rdfService.GetDataSource(base+"/static/rdf/"+mytype+"s/"+id+"-"+dbVersion+".xml")
        f.database.AddDataSource(content_ds)
        f.ref=NS+"/"+mytype+"/"+id+"/contents"
        selectNav(mytype, id)
        if (mytype == "album") {
            $('album').collapsed = true
            $('album_art').src = base + "/static/rdf/covers/" + id + ".jpg"
            $('album_artBox').collapsed = false
        }
        else {
            $('album_art').src = ""
            $('album_artBox').collapsed = true
            $('album').collapsed = false
        }
    }
    else if(id=='top'){
        f.ref=NS+"/"+id+'_'+mytype+"s"
        $('album_art').src = ""
        $('album_artBox').collapsed = true
        $('album').collapsed = false
        }
    else {
        f.ref=NS+"/"+mytype+"s"
        $('album_art').src = ""
        $('album_artBox').collapsed = true
        $('album').collapsed = false
        }
}
function selectNav(mytype, id){
    var tree = $('navtree')
    var tid = -1
    var ttype = -1
    var ci = tree.currentIndex
    if (ci >= 0) {
        if (tree.view.selection.isSelected(ci)) {
            tid = tree.view.getCellValue(ci, tree.columns.getNamedColumn('navname'))
            ttype = tree.view.getCellValue(tree.currentIndex, tree.columns.getNamedColumn('navtype'))
        }
    }
    if (tid != id || ttype != mytype) {
        var builder = tree.builder
        var node = rdfService.GetResource(NS + "/" + mytype + "/" + id)
        var idx = builder.getIndexOfResource(node)
        if (idx != -1) {
            builder.root.view.selection.select(idx);
            var boxobject = tree.boxObject;
            boxobject.QueryInterface(Components.interfaces.nsITreeBoxObject);
            boxobject.ensureRowIsVisible(idx)
        }
        else {
            tree.view.selection.clearSelection()
            }
    }
}
function goBack(){
    if (wa2_history.length > 1) {
        wa2_future.unshift(wa2_history.shift())
        var loc = wa2_history.shift()
        var mytype = loc[0]
        var id = loc[1]
        getDir(mytype, id)
        $('files_forward').disabled = false
    }
    if (wa2_history.length <= 1) {$('files_back').disabled=true}
}
function goForward(){
    if (wa2_future.length > 0) {
        var loc = wa2_future.shift()
        var mytype = loc[0]
        var id = loc[1]
        getDir(mytype, id)
    }
    if (wa2_future.length == 0) {$('files_forward').disabled=true}
}


function album_art_click(){
    var art = $('album_art')
    var artBox = $('album_artBox')
    if (art.className == "scaled") {
        artBox.style.width = "250px"
        art.className = ""
        }
    else {
        art.className = "scaled"
        artBox.style.width = "150px"
        }
}
function files_dblclick() {
  var tree = $('files')
  var id = tree.view.getCellValue(tree.currentIndex,tree.columns.getNamedColumn('name'))
  var mytype = tree.view.getCellValue(tree.currentIndex,tree.columns.getNamedColumn('type'))
  if (mytype == "file") {send("/doCommand?action=add&val="+id)}
  else {
    var tree = $('navtree')
    if (!tree.view.isContainerOpen(tree.currentIndex)) {
        tree.view.toggleOpenState(tree.currentIndex)
    }
    getDir(mytype, id)
    }
  }


function files_googleIt() {
  var tree = $('files')
  var id = tree.view.getCellText(tree.currentIndex,tree.columns.getNamedColumn('title'))
  var mytype = tree.view.getCellValue(tree.currentIndex,tree.columns.getNamedColumn('type'))
  google(id, mytype)
  }
function files_lyricsfreak() {
  var tree = $('files')
  var id = tree.view.getCellText(tree.currentIndex,tree.columns.getNamedColumn('title'))
  var mytype = tree.view.getCellValue(tree.currentIndex,tree.columns.getNamedColumn('type'))
  lyricsfreak(id, mytype)
  }
function files_info(){
  var tree = $('files')
  var id = tree.view.getCellValue(tree.currentIndex,tree.columns.getNamedColumn('name'))
  openURL(base+"/song_info?id="+id)
}
function nav_googleIt() {
  var tree = $('navtree')
  var id = tree.view.getCellText(tree.currentIndex,tree.columns.getNamedColumn('navname'))
  var mytype = tree.view.getCellValue(tree.currentIndex,tree.columns.getNamedColumn('navtype'))
  google(id, mytype)
  }
function nav_lyricsfreak() {
  var tree = $('navtree')
  var id = tree.view.getCellText(tree.currentIndex,tree.columns.getNamedColumn('navname'))
  var mytype = tree.view.getCellValue(tree.currentIndex,tree.columns.getNamedColumn('navtype'))
  lyricsfreak(id, mytype)
  }


function nav_add() {
  var tree = $('navtree')
  var id = tree.view.getCellValue(tree.currentIndex,tree.columns.getNamedColumn('navname'))
  var mytype = tree.view.getCellValue(tree.currentIndex,tree.columns.getNamedColumn('navtype'))
  switch (mytype) {
    case "artist": send("/doCommand?action=addart&val="+id); break;
    case "album": send("/doCommand?action=addalb&val="+id); break;
    case "dir": send("/doCommand?action=adddir&val="+id); break;
    case "playlist": send("/doCommand?action=addpls&val="+id); break;
    }
  }
function nav_replace() {
    sendCB("/doCommand?action=clear", nav_add)
  }
function add() {
  var tree=$("files")
  var artists = new Array()
  var albums = new Array()
  var dirs = new Array()
  var songs = new Array()
  var playlists = new Array()
  var start = new Object();
  var end = new Object();
  var numRanges = tree.view.selection.getRangeCount();

  for (var t=0; t<numRanges; t++){
    tree.view.selection.getRangeAt(t,start,end);
    for (var v=start.value; v<=end.value; v++){
      var id = tree.view.getCellValue(v, tree.columns.getNamedColumn ('name'))
      var itemtype = tree.view.getCellValue(v, tree.columns.getNamedColumn('type'))
      switch (itemtype) {
        case "artist": artists.push(id);break;
        case "album": albums.push(id);break;
        case "dir": dirs.push(id);break;
        case "file": songs.push(id); break;
        case "playlist": playlists.push(id); break;
        }
      }
    }
  if (artists.length > 0) {
    ids = createURLranges(artists)
    send("/doCommand?action=addart&val="+ids)
    }
  if (albums.length > 0) {
    ids = createURLranges(albums)
    send("/doCommand?action=addalb&val="+ids)
    }
  if (dirs.length > 0) {
    ids = createURLranges(dirs)
    send("/doCommand?action=adddir&val="+ids)
    }
  if (songs.length > 0) {
    ids = createURLranges(songs)
    send("/doCommand?action=addfile&val="+ids)
    }
  if (playlists.length > 0) {
    ids = createURLranges(playlists)
    send("/doCommand?action=addpls&val="+ids)
    }
  }
function replace(){
    sendCB("/doCommand?action=clear", add)
}
function nav_rescan(){
    send("/doCommand?action=update")
    $('files').disabled = true
    $('navtree').disabled = true
    var browse = $('browse')
    if (browse) {
        alert('Update in progress...\nReopen page when complete.')
        window.close()
    }
}
function nav_collapse() {
    var treeView = $('navtree').view
    for (var i=(treeView.rowCount-1);i>=0;i--) {
        if (i>=treeView.rowCount) {i=treeView.rowCount-1}
           if (treeView.isContainer(i) && treeView.isContainerOpen(i)){
            treeView.toggleOpenState(i);
            }
        }
    }
function show_search(items){
    $('navtree').view.selection.clearSelection()
    var f = $('files')
    if (content_ds) {
      f.database.RemoveDataSource(content_ds)
      }
    var rdfString ='<RDF:RDF xmlns:RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#" ' +
                        'xmlns:s="'+NS+'">\n' +
                        '<RDF:Seq about="'+NS+'/search_results/contents">\n'
    for (x in items){
            rdfString += ' <RDF:li resource="'+NS+'/song/'+items[x]+'"/>\n'
            }
    rdfString += '</RDF:Seq></RDF:RDF>'
    content_ds = parseRDFString(rdfString, base+"/search_results")
    f.database.AddDataSource(content_ds)
    f.ref=NS+"/search_results/contents"
    f.builder.rebuild()
}
function search (what, where){
    get(base+"/search?what="+escape(what)+"&where="+where, show_search)
}
function search_clear () {
    var loc = wa2_history.shift()
    var mytype = loc[0]
    var id = loc[1]
    getDir(mytype, id)
}

